<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="formVisible" append-to-body width="500px">
      <el-form ref="myForm" :model="form" label-width="100px">
        <el-form-item label="头像" prop="avatar" required>
          <UploadFile :fs="avatar" @success="v=>form.avatar=v" />
        </el-form-item>
        <el-form-item label="用户名" prop="username" required>
          <el-input v-model="form.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="密码" required prop="password">
          <el-input v-model="form.password" placeholder="密码" type="password" />
        </el-form-item>
        <el-form-item label="姓名" required prop="name">
          <el-input v-model="form.name" placeholder="昵称" />
        </el-form-item>
        <el-form-item label="手机号码" required prop="phone">
          <el-input v-model="form.phone" placeholder="手机号码" />
        </el-form-item>
        <el-form-item label="状态" required prop="disabled">
          <el-select v-model="form.disabled" placeholder="选择是否禁用">
            <el-option label="启用" :value="false" />
            <el-option label="禁用" :value="true" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="用户角色" :visible.sync="allotVisible" append-to-body width="500px">
      <el-form :model="allotForm" label-width="100px">
        <el-form-item label="分配角色">
          <el-select v-model="allotForm.roleIds" multiple placeholder="请选择角色" style="width:100%">
            <el-option v-for="r in roleList" :key="r.id" :label="r.name" :value="r.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="allotVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitAllot">提交</el-button>
      </div>
    </el-dialog>
    <el-form :inline="true" size="small">
      <el-form-item label="用户名:">
        <el-input v-model="searchParams.search" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-circle-plus" @click="handleInsert">添加用户</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="头像">
        <template slot-scope="scope">
          <el-image style="width:40px;height:40px" fit="cover" :src="scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名">
        <template slot-scope="scope">{{ scope.row.username }}</template>
      </el-table-column>
      <el-table-column align="center" label="手机号码">
        <template slot-scope="scope">{{ scope.row.phone }}</template>
      </el-table-column>
      <el-table-column align="center" label="姓名">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.disabled" type="danger">禁用</el-tag>
          <el-tag v-if="!scope.row.disabled" type="success">启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="text" icon="el-icon-refresh-left" @click="handleOffline(scope.row)">强制下线</el-button>
          <el-button type="text" icon="el-icon-lock" @click="handleAllot(scope.row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div :style="{textAlign:'center',padding:'10px'}">
      <el-pagination
        background
        :current-page.sync="searchParams.pageNum"
        :page-sizes="[10, 20, 30, 40,50]"
        :page-size.sync="searchParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchParams.total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
  </div>
</template>

<script>
import { roleList } from '@/api/system/role'
import { delUser, offlineUser, saveUser, userList } from '@/api/system/user'
import { allotUserRoles, getUserRoles } from '@/api/system/user_role'
import UploadFile from '@/components/UploadFile'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  components: {
    UploadFile
  },
  data() {
    return {
      list: null,
      listLoading: true,
      formVisible: false,
      form: {},
      allotVisible: false,
      allotForm: {},
      roleList: [],
      avatar: [],
      searchParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        search: ''
      },
      title: ''
    }
  },
  created() {
    this.fetchData()
    roleList().then(res => {
      this.roleList = res.data.records
    })
  },
  methods: {
    handleAllot(row) {
      getUserRoles(row.id).then(res => {
        this.allotForm = {
          roleIds: res.data,
          userId: row.id
        }
        this.allotVisible = true
      })
    },
    handleSubmitAllot() {
      this.$confirm('确定为用户分配角色吗？', '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      }).then(() => {
        allotUserRoles(this.allotForm).then(() => {
          this.$message.success('分配角色成功')
          this.allotVisible = false
        })
      })
    },
    handleOffline(row) {
      this.$confirm('确定强制用户下线吗？', '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      }).then(() => {
        offlineUser(row.username).then(() => {
          this.$message.success('下线成功')
        })
      })
    },
    handleUpdate(row) {
      this.title = '修改用户信息'
      this.formVisible = true

      this.$nextTick(() => {
        this.$refs['myForm'].resetFields()
        this.form = { ...row }
        this.avatar = [row.avatar]
      })
    },
    handleInsert() {
      this.avatar = []
      this.formVisible = true
      this.title = '添加用户信息'
      this.$nextTick(() => {
        this.$refs['myForm'].resetFields()
        this.form = {}
      })
    },
    handleSubmit() {
      this.$refs['myForm'].validate(valid => {
        if (valid) {
          saveUser(this.form).then(() => {
            this.$message.success('保存信息成功')
            this.fetchData()
            this.formVisible = false
          })
        }
      })
    },
    handleDelete({ id }) {
      this.$confirm('确认删除此信息吗？', '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      }).then(() => {
        delUser(id).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      })
    },
    fetchData() {
      this.listLoading = true
      userList(this.searchParams).then(response => {
        const { records, total } = response.data
        this.list = records
        this.searchParams.total = total
        this.listLoading = false
      })
    }
  }
}
</script>

